package top.lingkang.finalvalidated.handle;

import top.lingkang.finalvalidated.constraints.Email;
import top.lingkang.finalvalidated.core.FinalValidatorFactory;
import top.lingkang.finalvalidated.error.CheckException;
import top.lingkang.finalvalidated.error.ValidatedException;
import top.lingkang.finalvalidated.utils.FinalValidatorUtils;

import java.util.regex.Pattern;

/**
 * @author lingkang
 * Created by 2024/1/28
 */
public class EmailHandle extends ValidHandle {
    private final String errorStr;
    private final Pattern pattern;
    private final Email email;

    public EmailHandle(ValidVal validVal, Email email) {
        super(validVal, email);
        this.email = email;

        if (FinalValidatorUtils.isBlank(email.value())) {
            throw new CheckException("@Email 所配置的正则表达式(value)不能为空！字段属性：" + validVal.getName());
        }
        if (FinalValidatorUtils.isNotEmpty(email.message())) {
            errorStr = email.message();
        } else if (FinalValidatorUtils.isNotEmpty(validVal.getTag())) {
            errorStr = FinalValidatorFactory.message.getProperty("Email")
                    .replace("{attrName}", validVal.getTag());
        } else {
            errorStr = FinalValidatorFactory.message.getProperty("Email")
                    .replace("{attrName}", validVal.getName());
        }
        pattern = Pattern.compile(email.value());
    }

    @Override
    public void valid(Object target) {
        Object o = validVal.getValGet().get(target);
        if (o == null || !pattern.matcher(o.toString()).matches()) {
            throw new ValidatedException(errorStr, validVal);
        }
    }

    @Override
    public Class<?>[] getGroups() {
        return email.groups();
    }
}
